package com.obrempon.credit.market.ui.fragment

import android.graphics.Color
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.obrempon.credit.market.R
import com.obrempon.credit.market.common.CommonFragment
import com.obrempon.credit.market.configs.ObremponApiUrl.addCommonParams
import com.obrempon.credit.market.databinding.ObremponAuthStepCommonFragmentBinding
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.ui.activity.ObremponAuthStepsAct
import com.obrempon.credit.market.ui.adapter.ObremponAuthStepCommonApt
import com.obrempon.credit.market.ui.dialog.ObremponBirthdayDialog
import com.obrempon.credit.market.ui.popupwindow.ObremponCommonPopupwindow
import com.obrempon.credit.market.utils.ObremponDensityUtil
import com.obrempon.credit.market.utils.decoration.LinearSpacingItemDecoration
import com.obrempon.credit.market.utils.log.ObremponLogger
import org.json.JSONObject

/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/19 14:19
 * @Annotation：认证流程 - 通用
 */
class ObremponAuthStepCommonFragment(): CommonFragment() {
    lateinit var binding: ObremponAuthStepCommonFragmentBinding
    private var stepItem: JSONObject? = null
    private var eventRemark = ""

    private var generalAdapter: ObremponAuthStepCommonApt? = null
    private var mSelectPosition = -1

    //出生日期选择
    private var birthdayDialog: ObremponBirthdayDialog? = null

    constructor(data: JSONObject): this(){
        this.stepItem = data
        this.eventRemark = data.optString("stepTitle")
    }

    override fun getObremponRootView(inflater: LayoutInflater): View {
        binding = ObremponAuthStepCommonFragmentBinding.inflate(inflater)
        return binding.root
    }

    override fun initObremponView() {
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#00000000"))
        initAuthStepListView()
    }

    override fun initObremponListener() {
        //下一步
        binding.authStepCommonNext.setOnClickListener {
            if (stepItem == null){
                return@setOnClickListener
            }
            if (!isAllowCommonSubmit()){
                showErrorTipsDialog(getString(R.string.obrempon_dialog_tips_submit_error), eventRemark)
                return@setOnClickListener
            }
            val params = JSONObject().addCommonParams().apply {
                put("path", stepItem!!.optString("apiUrl").replace("/",""))
            }
            for (i in 0..<generalAdapter!!.itemCount){
                val item = generalAdapter!!.getItem(i)
                if (item.has("selectItem")){
                    val selectItem = item.optJSONObject("selectItem")
                    if (selectItem != null){
                        params.put(item.optString("paramName"),selectItem.optString("value"))
                    }
                }
            }
            ObremponLogger.e(">>>>>>submit data >>>>>>>$params")
            val act = getAct() as ObremponAuthStepsAct
            act.onObremponAuthStepSubmitAction(params)

            addEventPointRequestAction(String.format(ObremponEventPointType.CLICK.OBREMPON_CLICK_STEP_XX_NEXT, eventRemark),"")
        }
    }

    override fun takeObremponData() {
        if (eventRemark == "personal_info"){
            val showKey = getString(R.string.obrempon_auth_step_personal_info_data_security_key)
            val showText = String.format(getString(R.string.obrempon_auth_step_personal_info_data_security),showKey)
            val startIndex = showText.indexOf(showKey)
            val dataSecuritySpannable = SpannableString(showText)
            dataSecuritySpannable.setSpan(ForegroundColorSpan(getColor(R.color.color_ffff7226)), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            //加粗
            dataSecuritySpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            binding.textPersonalInfoDataSecurity.text = dataSecuritySpannable
            binding.textPersonalInfoDataSecurity.visibility = View.VISIBLE

            //个人信息额度增加数额 = 产品额度 / 2 * 0.05
            binding.textCreditLimitAddAmount.text = String.format(getString(R.string.obrempon_auth_step_credit_limit_add),stepItem?.optString("creditLimitAmount"))
            binding.creditLimitAddLayout.visibility = View.VISIBLE
        } else {
            binding.textPersonalInfoDataSecurity.visibility = View.GONE
            binding.creditLimitAddLayout.visibility = View.GONE
        }

        val dataList = arrayListOf<JSONObject>()
        if (stepItem != null){
            addEventPointRequestAction(String.format(ObremponEventPointType.PAGE.OBREMPON_PAGE_STEP_COMMON_XX_START,eventRemark),"")

            val dataArray = stepItem?.optJSONArray("dataList")
            if (dataArray != null) {
                for (i in 0..<dataArray.length()){
                    dataList.add(dataArray.optJSONObject(i))
                }
            }
        }
        generalAdapter?.data = dataList
    }

    /**
     * 初始化Views
     */
    private fun initAuthStepListView(){
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.authStepCommonListView.layoutManager = layoutManager
        val topDecoration = ObremponDensityUtil.dp2px(14f)
        binding.authStepCommonListView.addItemDecoration(LinearSpacingItemDecoration(0, 0, 0, topDecoration))
        generalAdapter = ObremponAuthStepCommonApt(binding.authStepCommonListView)
        binding.authStepCommonListView.adapter = generalAdapter
        binding.authStepCommonListView.itemAnimator = DefaultItemAnimator()
        generalAdapter!!.setOnItemChildClickListener { _, childView, position ->
            binding.root.clearFocus()
            mSelectPosition = position
            val item = generalAdapter!!.getItem(position)
            when (item.optString("action")) {
                "DATE_PICK" -> {//时间选择
                    showObremponAuthStepBirthdayDialog()
                }
                "SELECT" -> {//选择
                    val dataList = arrayListOf<JSONObject>()
                    val dataArray = item.optJSONArray("values")
                    if (dataArray != null) {
                        for (i in 0..<dataArray.length()) {
                            dataList.add(dataArray.optJSONObject(i))
                        }
                    }
                    showSelectPopupwindow(childView, dataList)
                }
            }
        }
    }

    /**
     * 选择选项
     */
    private fun showSelectPopupwindow(view: View,dataList: ArrayList<JSONObject>){
        val selectPopup = ObremponCommonPopupwindow(requireContext())
        selectPopup.setWindowWidth(view.width + ObremponDensityUtil.dp2px(10f))
        selectPopup.setSelectItemListener(object : ObremponCommonPopupwindow.IItemClickListener {
            //完成
            override fun onConfirmAction(data: JSONObject?) {
                val item = generalAdapter!!.getItem(mSelectPosition)
                item.put("selectItem",data)
                generalAdapter!!.notifyItemChanged(mSelectPosition)

                if (data != null){
                    val subRemark = "${data.optString("value")}$$${data.optString("duration")}"
                    addEventPointRequestAction(String.format(ObremponEventPointType.CLICK.OBREMPON_CLICK_STEP_XX_SELECT,item.optString("paramName")),subRemark)
                }
            }
            //关闭监听
            override fun onDismissListener() {
            }
        })
        selectPopup.show(view, binding.root)
        selectPopup.setBrandList(dataList)
    }

    private fun showObremponAuthStepBirthdayDialog(){
        if (birthdayDialog == null){
            birthdayDialog = ObremponBirthdayDialog(requireContext(),eventRemark,object : ObremponBirthdayDialog.IDialogCallback{
                override fun completed(selectDate: JSONObject) {
                    //可根据需要自行截取数据显示
                    val item = generalAdapter!!.getItem(mSelectPosition)
                    val obj = JSONObject()
                    obj.put("title",selectDate.optString("showDate"))
                    obj.put("title_sw",selectDate.optString("showDate"))
                    obj.put("value",selectDate.optString("subDate"))
                    item.put("selectItem",obj)
                    generalAdapter!!.notifyItemChanged(mSelectPosition)

                    val subRemark = "${selectDate.optString("subDate")}$$${selectDate.optString("duration")}"
                    addEventPointRequestAction(String.format(ObremponEventPointType.CLICK.OBREMPON_CLICK_STEP_XX_SELECT,item.optString("paramName")),subRemark)
                }
            })
        }
        birthdayDialog!!.show()
    }

    /**
     * 通用类型列表
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowCommonSubmit(): Boolean{
        //是否允许提交
        var isAllow = true
        for (i in 0..<generalAdapter!!.itemCount){
            val item = generalAdapter!!.getItem(i)
            //存在 isMust && isMust == ”NO“  非必填
            if (item.has("isMust") && item.optString("isMust") == "NO"){
                continue
            }
            //必填 && 没有内容 || 内容为空
            if (!item.has("selectItem") || item.optJSONObject("selectItem")?.optString("value")!!.isEmpty()){
                isAllow = false
                break
            }
        }
        return isAllow
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(String.format(ObremponEventPointType.PAGE.OBREMPON_PAGE_STEP_COMMON_XX_END,eventRemark),"")
    }
}